package com.bete.otherutils;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static java.lang.Thread.sleep;

import android.Manifest;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ShellUtils;
import com.blankj.utilcode.util.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import me.jessyan.autosize.utils.LogUtils;


public class SplashActivity extends BaseActivity {
    private Context context;
    private static final int REQUEST_PERMISSION_CODE = 0;
    private boolean animationStarted = false;
    private List<ApplicationInfo> mListAppcations;
    private PackageManager mPackageManager;
    int process = 0;
    TextView tv_product;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        context = this;
        new Thread() {
            @Override
            public void run() {
                super.run();
                requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);//, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_SECURE_SETTINGS, Manifest.permission.CAMERA
            }
        }.start();
    }

    protected void initView() {
        tv_product = findViewById(R.id.tv_product);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_splash;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    /*
      权限相关的操作
     */
    public void permissionSuccess(int requestCode) {
        if (requestCode == REQUEST_PERMISSION_CODE) {
            LogUtils.d("获取权限成功:" + requestCode);

            FileCommonUtil.createOrExistsDir("/sdcard/updataapk");
            String packagename = "com.bete.update";
            // 0. 将 软件复制到目的之中
            copyDir("updataapk");
            // 0. 判断软件是否安装
            ShellUtils.CommandResult commandResult = ShellUtils.execCmd(" pidof " + packagename, true);
            LogUtils.d(" commandResult : " + commandResult.result);
            if (commandResult.result > 0) {
//                commandResult = ShellUtils.execCmd("uninstall " + packagename, true);
//                LogUtils.d(" commandResult : " + commandResult.result);
//                if (commandResult.result > 0) {
                commandResult = ShellUtils.execCmd("pm install -r sdcard/updataapk/updata.apk", true);

                LogUtils.d(" commandResult : " + commandResult.result);
//                if (isInstall(packagename)) {
//                    LogUtils.d(" 软件安装成功 ");
//                } else {
//                    LogUtils.d(" 软件安装失败 ");
//                }
//                }
            }
            // 1. 卸载软件
//            ShellUtils.CommandResult commandResult = ShellUtils.execCmd("uninstall "+ packagename, true);


            // 3. 安装软件

            try {
                sleep(1000);
            } catch (InterruptedException e) {
                LogUtils.d(e.toString());
            }


            startNextActivity();
        } else {
            throw new IllegalStateException("Unexpected value: " + requestCode);
        }
    }

    /**
     * 判断软件是否安装
     *
     * @return
     */
    public boolean isInstall(String name) {
        mPackageManager = context.getPackageManager();
        mListAppcations = mPackageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        for (ApplicationInfo info : mListAppcations) {
//            LogUtils.e("getPackagename: ---" + info.packageName);
            // 匹配QQ的包名 如果手机中安装了QQ
            if (info.packageName.equals(name)) {
                LogUtils.d("isInstall " + name + true);
                return true;
            }
        }
        LogUtils.d("isInstall " + name + false);
        return false;
    }

    /**
     * 判断是否第一次登录
     */
    private void startNextActivity() {
        startActivity(new Intent(this, MainActivity.class));

    }


    /**
     * 请求权限
     *
     * @param permissions           请求的权限
     * @param requestPermissionCode 请求码
     */
    private int REQUEST_CODE_PERMISSION = 0x00099;

    public void requestPermission(String[] permissions, int requestPermissionCode) {
        REQUEST_CODE_PERMISSION = requestPermissionCode;
        if (checkPermissions(permissions)) {
            // 同意权限
            permissionSuccess(requestPermissionCode);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
        }
    }

    /**
     * 检测所有的权限是否都已授权
     *
     * @param permissions
     * @return
     */
    public boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < 23) {
            return true;
        }
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) !=
                    PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(REQUEST_CODE_PERMISSION);
            } else {
                permissionFail(REQUEST_CODE_PERMISSION);
                showTipsDialog();
            }
        }
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle(getString(R.string.tipInfo))
                .setMessage(getString(R.string.splashTipInfo))
                .setNegativeButton(getString(R.string.cancel), (dialog, which) -> AppUtils.exitApp())
                .setPositiveButton(getString(R.string.queding), (dialog, which) -> startAppSettings()).show();
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 权限获取失败
     *
     * @param requestCode
     */
    public void permissionFail(int requestCode) {
        LogUtils.d("获取权限失败:" + requestCode);
    }

    /**
     * 确认所有的权限是否都已授权
     *
     * @param grantResults
     * @return
     */
    public boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     */
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PERMISSION_GRANTED || ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needRequestPermissionList.add(permission);
            }
        }
        return needRequestPermissionList;
    }

    private void copyDir(String path) {
        String[] files;
        try {
            files = this.getAssets().list(path);
            if (files.length == 0) {
                copyFile(path);
            } else {
                String filePath = "/sdcard" + "/" + path;
                File file = new File(filePath);
                if (FileCommonUtil.isFileExists(filePath)) {
                    FileCommonUtil.deleteDirOrFile(filePath);
                    FileCommonUtil.createOrExistsDir(filePath);
                }
                file.mkdirs();
                for (int i = 0; i < files.length; i++) {
                    String[] files2 = this.getAssets().list(path + "/" + files[i]);
                    if (files2.length == 0) {
                        copyFile(path + "/" + files[i]);
                    } else {
                        copyDir(path + "/" + files[i]);
                    }
                }

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            LogUtils.d(e.toString());
        }
    }

    private void copyFile(String path) {
        LogUtils.d("file" + path);
        InputStream in = null;
        FileOutputStream out = null;
        try {
            String filePath = "/sdcard" + "/" + path;
            File file = new File(filePath);
            if (!file.exists()) {
                in = this.getAssets().open(path);
                out = new FileOutputStream(file);
                int length = -1;
                byte[] buf = new byte[1024];
                while ((length = in.read(buf)) != -1) {
                    out.write(buf, 0, length);
                }
                out.flush();
                in.close();
                out.close();
            }
        } catch (IOException e) {
            LogUtils.d(e.toString());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                LogUtils.d(e.toString());
            }
        }
    }

}
